#! /usr/bin/python

####
# launch all the slaves
#### 
import sys
import os
import subprocess
import ConfigParser
import logging

###### parameter parsing #####
if len(sys.argv) < 2:
	print 'usage'
	print '-----'
	print ''
	print 'launch.py config_file'
	print ' '
	print ' '
	print 'Inputs:'
	print '-------'
	print 'The configuration file that discribes the jobs and the dispatching setup.'
	print 'For more information please refer to the in-line comments in the example.conf.'
	sys.exit(1)

###### read in configuration file ##### 
config=ConfigParser.SafeConfigParser()
config_file = os.path.abspath(os.path.expanduser(sys.argv[1]))
if os.path.exists(config_file):
    config.read(config_file)
else:
    print 'config_file does not exist'
    sys.exit(1)

job_id = config_file.split('/')[-1].split('.conf')[0]  

working_dir = os.path.expanduser(config.get('MASTER','working_directory'))
slaves_list=config.get('MASTER','slaves').split(',')
slaves_list=map(lambda name: name.strip(), slaves_list)  # convert to IP addresses

launch_log_file = working_dir+'/'+job_id+'.launch.log' 
log_level = config.getint('MASTER', 'log_level')
logger = logging.getLogger("launch")
fh = logging.FileHandler(launch_log_file,"w")
fh.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
if log_level <= logging.INFO:  # in debugging mode, displace logs to stdout
    ch = logging.StreamHandler()
    ch.setLevel(log_level)
    ch.setFormatter(formatter)
    logger.addHandler(ch)

###### start working now! ####
null_fd=open("/dev/null",'w')
for slave in slaves_list:
    try:
        subprocess.Popen(["ssh", slave, "killall", "-u", "xqwang"], stdout=null_fd, stderr=null_fd)
    except:
        logger.info("%s is not launched.",slave) 
    else:
        logger.info("%s is launched successfully.",slave) 
